import dayjs from 'dayjs';
import { round } from 'lodash';
import { ACTIVE_KEY, SETTLEMENT_TYPE, ACTIVITY_TAG, ACTIVITY_GOODS_STATUS } from '@/config/constants';

/**
 * @method 网上抄的深拷贝方法
 * @param obj 需要深拷贝的对象
 */
export function deepClone(obj: any) {
  let objClone: any = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === 'object') {
    for (let key in obj) {
      if (obj[key] && typeof obj[key] === 'object') {
        objClone[key] = deepClone(obj[key]);
      } else {
        objClone[key] = obj[key];
      }
    }
  }
  return objClone;
}

/**
 * @method 获取活动状态
 * @param data 活动数据
 */
export function getActivityStatus(data: Record<string, any> = {}): Record<string, any> {
  return {
    NOT_START: {
      key: ACTIVE_KEY.NOT_START,
      text: '未开始',
      color: 'rgba(254,80,35,0.3)',
      remindTxt: `将于${data.enrollStartTime}开始报名`,
    },
    PROCESS: () => {
      const diffDay = dayjs(data.enrollEndTime).diff(dayjs(), 'day');
      const diffHour = dayjs(data.enrollEndTime).diff(dayjs(), 'hour');
      const diffMinute = dayjs(data.enrollEndTime).diff(dayjs(), 'minute');
      const remindTxt =
        diffHour >= 24
          ? `${diffDay}天${diffHour}小时后结束报名`
          : `${diffHour}小时${round(diffMinute - 60 * diffHour)}分钟后结束报名`;
      return {
        key: ACTIVE_KEY.PROCESS,
        text: '报名中',
        color: '#3478FD',
        remindTxt,
      };
    },
    NOT_MAK_PUBLIC: {
      key: ACTIVE_KEY.NOT_MAK_PUBLIC,
      text: '等待开标',
      color: '#FFB600',
      remindTxt: `已截止，${dayjs(data.resultPublicTime).format('MM-DD HH:mm')}前公布结果`,
    },
    MAKE_PUBLIC: () => {
      const { tagForManager, sellerManagerReviewWinCount } = data;
      // 未参加
      const isUnCommitted = tagForManager === ACTIVITY_TAG.UNCOMMITTED.key;
      // 已审核
      const isManagerReviewed = tagForManager === ACTIVITY_TAG.MANAGER_REVIEWED.key;
      // 中标商品数量
      const winCount = data.goodsManagerReviewWinCount;

      // 已结束按钮文案
      const endBtnExtraTxt =
        winCount <= 0 && !isUnCommitted
          ? { btntxt: '未中标', remindTxt: '很遗憾，所有商家均未中标，需加大价格控制' }
          : { btntxt: '未参加', remindTxt: '已公布结果，未参加报名！' };

      return {
        key: ACTIVE_KEY.MAKE_PUBLIC,
        text: '已结束',
        color: '#8C8C8C',
        btnTxt: isManagerReviewed ? '查看' : '',
        btnColor: isManagerReviewed ? '#3478FD' : '',
        btnBgColor: isManagerReviewed ? '#fff' : '',
        remindTxt:
          winCount > 0 ? `恭喜${sellerManagerReviewWinCount}个商家中标${winCount}个商品` : endBtnExtraTxt.remindTxt,
      };
    },
  };
}

/**
 * @method 获取活动标签
 * @param data 活动数据
 */
export function getActivityTag(data: Record<string, any> = {}): Record<string, any> {
  return {
    UNCOMMITTED: {
      ...ACTIVITY_TAG.UNCOMMITTED,
      color: '#BFBFBF',
    },
    MANAGER_WAIT_DETERMINE: {
      ...ACTIVITY_TAG.MANAGER_WAIT_DETERMINE,
      color: '#F7BE00',
      btnTxt: `审核(${data.goodsManagerWaitDetermineCount})`,
      btnBgColor: '#3478FD',
      remindTxt: `有${data.goodsManagerWaitDetermineCount}个商品需要审核价格和库存`,
    },
    MANAGER_REVIEWED: {
      ...ACTIVITY_TAG.MANAGER_REVIEWED,
      color: '#69B146',
    },
  };
}

/**
 * @method 获取商品状态
 * @param activityStatus 活动状态
 */
export function getGoodsStatus(activityStatus: string = ''): Record<string, any> {
  const rightTxt = activityStatus !== ACTIVE_KEY.MAKE_PUBLIC ? '等待开标' : '';
  return {
    MANAGER_WAIT_DETERMINE: {
      ...ACTIVITY_GOODS_STATUS.MANAGER_WAIT_DETERMINE,
      tagTxt: '待确认',
      color: '#F7BE00',
      rightTxt: rightTxt,
      rightTxtColor: '#F7BE00',
    },
    MANAGER_REVIEW_FAIL: {
      ...ACTIVITY_GOODS_STATUS.MANAGER_REVIEW_FAIL,
      tagTxt: '已打回',
      color: '#BFBFBF',
      rightTxt: rightTxt,
      rightTxtColor: '#F7BE00',
    },
    AUDIT: {
      ...ACTIVITY_GOODS_STATUS.AUDIT,
      tagTxt: '已通过',
      color: '#69B146',
      rightTxt: rightTxt,
      rightTxtColor: '#F7BE00',
    },
    WIN: {
      ...ACTIVITY_GOODS_STATUS.WIN,
      icon: 'icon_yizhongbiao',
      color: '#69B146',
    },
    FLUNK: {
      ...ACTIVITY_GOODS_STATUS.FLUNK,
      icon: 'icon_weizhongbiao',
      color: '#BFBFBF',
    },
  };
}

/**
 * 是否是标品
 * @param type
 * @returns {boolean}
 */
export const isStander = (type: string) => SETTLEMENT_TYPE.key.STANDER === type;

/**
 * @method 计算预估收益
 * @param basePrice 基础价格
 * @param rate
 * @returns {string}
 */
export const calcBenefit = (basePrice = 0, rate = 0) => {
  rate = rate || 0;
  return basePrice && basePrice !== 0 ? round(basePrice * (1 - rate / 100), 2) : '';
};

/**
 * @method 判断是否是函数
 * @param fn
 */
const isFunc = (fn: any) => (typeof fn === 'function' ? fn() : fn);

/**
 * @method 获取状态
 * @param fn 执行的方法
 * @param data 数据
 * @param key 状态key
 */
export const getStatus = (fn: Function, data: Record<string, any> = {}, key: string) => {
  const statusEnum = fn(data) as any;

  return isFunc(statusEnum[data[key]] ?? {});
};

export function isNotEmpty(str: any) {
  return str !== null && str !== undefined;
}

/**
 * 拼接地址
 * @param province
 * @param city
 * @param county
 * @param address
 * @param separator
 * @returns {string}
 */
export const handleFullAddress = (province = '', city = '', county = '', address = '', separator = ' ') => {
  const paddingSpace = (str: string) => (str ? `${str}${separator}` : str || '');
  return `${paddingSpace(province)}${paddingSpace(city)}${paddingSpace(county)}${address || ''}`;
};

/**
 * @method 活动报名要求文案
 * @param data
 */
export const getActivityDemandTxt = (data: Record<string, any>) => {
  let str = '';
  const videoTxt = data.needUpdateVideo ? '所有报名商品视频需当日更新' : '';
  const priceTxt = data.lowerProportion ? `提报价格需低于常规价${round(data.lowerProportion * 100)}%` : '';

  if (data.needUpdateVideo && data.lowerThanRegularPrice) {
    str = `${videoTxt}${priceTxt ? '，' + priceTxt : ''}`;
  } else if (data.lowerThanRegularPrice) {
    str = data.lowerProportion ? `所有报名商品${priceTxt}` : '';
  } else if (data.needUpdateVideo) {
    str = videoTxt;
  }
  return str;
};

// 价格驼峰
export function splitPrice(price: number | string | undefined = 0) {
  const dealPrice = isNotEmpty(price) ? round(Number(price), 2).toFixed(2) : '';
  let [firstArr, lastArr] = dealPrice.split('.');
  return [firstArr, lastArr];
}

export function debounce(method: any, wait: number): any {
  let timeout: any, result;
  let debounced = function (...args: any) {
    return new Promise((resolve) => {
      // @ts-ignore
      const context = this;
      if (timeout) {
        clearTimeout(timeout);
      }
      timeout = setTimeout(() => {
        result = method.apply(context, args);
        // 将原函数的返回值传给resolve
        resolve(result);
      }, wait);
    });
  };

  return debounced;
}
